import React from 'react'

import '@/assets/css/confirm.css'
import '@/assets/css/guestchoose.css'

const Confirm = () => {

    // 接收跳转参数
    const [searchParams] = React.Router.useSearchParams()


    let [rid, SetRid] = React.useState(searchParams.get('rid') ? searchParams.get('rid') : 0)

    let [show, SetShow] = React.useState(false)

    let [showguest, SetShowguest] = React.useState(false)
    let [selected, SetSelected] = React.useState('')



    let [room, SetRoom] = React.useState({
        thumb_text: '',
        name: '',
        flag_text: [],
        service_text: [],
        price: '0',
        area: 0,
        live: 0
    })

    let today = new Date()    
    let tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() +1)
    let todaystr = today.toLocaleDateString()
    let tomorrowstr = tomorrow.toLocaleDateString()
    let defaultday: any = `${todaystr} - ${tomorrowstr}`
    // console.log(defaultday)

    let [order, SetOrder] = React.useState({
        busid: React.Business.id,
        roomid: rid,
        guest: '',
        origin_price: room.price,
        price: '',
        starttime: Date.parse(today.toLocaleString()) / 1000,
        endtime: Date.parse(tomorrow.toLocaleString()) / 1000,
        couponid: '',
        couponstr: '',
        datestr: defaultday,
        days: 1,
        gueststr: '',
        guestids: []
    })

    let [price, SetPrice] = React.useState(0)
    let [origin_price, SetOriginPrice] = React.useState(0)


    React.useEffect(() => {
        RoomInfo()
        GuestData()
        CouponData()
    }, [])



    React.useEffect(() => {
        total()
    }, [order,room])

    let [guest, SetGuest] = React.useState([])
    let [coupon, SetCoupon] = React.useState([])
    let [CouponShow, SetCouponShow] = React.useState(false)


    // 房间数据
    const RoomInfo = async () => {
        var result = await React.HTTP.post('/room/info', { id: rid })

        if (result.code == 0) {
            React.error(result.msg)
            return false
        } else {
            SetRoom(result.data)
        }
    }


    // 日期改变
    const DateChange = (val: any) => {
        SetShow(false)
        var datestr = `${new Date(val[0]).toLocaleDateString()} - ${new Date(val[1]).toLocaleDateString()}`

        var starttime = Date.parse(new Date(val[0]).toLocaleString()) / 1000
        var endtime = Date.parse(new Date(val[1]).toLocaleString()) / 1000

        var days = Math.floor((endtime - starttime) * 1000 / (24 * 3600 * 1000))

        if (days < 0) {
            days = days * (-1)
        }

        // console.log(days)

        SetOrder({
            ...order,
            starttime,
            endtime,
            datestr,
            days
        })
    }

    // 住户数据
    const GuestData = async () => {
        var result = await React.HTTP.post('/room/guest', { busid: React.Business.id })

        if (result.code == 0) {
            return false
        } else {
            // console.log(result.data)
            SetGuest(result.data)
        }
    }

    // 优惠券数据
    const CouponData = async () => {
        var result = await React.HTTP.post('/room/coupon', { busid: React.Business.id })

        if (result.code == 1) {
            var list: any = []
            result.data.map((item: any) => {
                list.push({
                    label: `${item.coupon.title} - ${item.coupon.rate * 10}折`,
                    value: item.id,
                    rate: item.coupon.rate
                })
            })

            list = [list]
            SetCoupon(list)
        }
    }

    // 选择住户
    const guestchange = (val: any) => {
        SetSelected(val)

        var gueststr: any = [];
        var guestids: any = []

        guest.map((item: any) => {
            if (val.includes(item.id)) {
                gueststr.push(item.nickname)
                guestids.push(item.id)
            }
        })

        if(guestids.length > room.live){
            React.error("超出房间人数上限",() => {
                gueststr = []
                guestids = []
                SetOrder({
                    ...order,
                    gueststr: '',
                    guest: '',
                    guestids
                })
            })
            
            SetSelected('')
        }

        var str = gueststr.join(',')
        var ids = guestids.join(',')

        SetOrder({
            ...order,
            gueststr: str,
            guest: ids,
            guestids
        })
    }


    // 选择优惠券
    const CounponConfirm = (val: any) => {
        // console.log(val)
        SetCouponShow(false)

        var couponstr = ''

        var list: any = coupon[0]
        // console.log(list)
        list.map((item: any) => {
            if(item.value == val[0]){
                couponstr = item.label
            }
        })

        SetOrder({
            ...order,
            couponstr,
            couponid: val[0]
        })
    }


    // 计算价格
    const total = () => {
        var origin_price = order.days * parseFloat(room.price)
        var price = origin_price

        // 是否选择优惠券
        if(order.couponid){
            var rate = 1
            var list: any =  coupon[0]

            list.map((item: any) => {
                if(item.value == order.couponid){
                    rate = item.rate
                }
            })

            price = origin_price * rate
        }

        SetPrice(price)
        SetOriginPrice(origin_price)
    }


    const submit = async () => {
        var result = await React.UI.Dialog.confirm({
            content: '是否确认提交订单'
        })

        if(!result){
            return false
        }

        // 组装数据
        var data = {
            busid: React.Business.id,
            roomid: rid,
            cid: order.couponid ? order.couponid : 0,
            oprice: origin_price,
            price: price,
            starttime: order.starttime,
            endtime: order.endtime,
            guest: order.guest,
            days: order.days
        }

        // console.log(data)
        var result = await React.HTTP.post('/room/add',data)

        if(result.code == 0){
            React.error(result.msg,() => {})
            return false
        }else{
            React.success(result.msg, () => {
                React.navigate('/business/order')
            })
        }

    }



    return (
        <>
            <React.UI.NavBar
                back='返回'
                onBack={() => { React.navigate(-1) }}
            >
                提交订单
            </React.UI.NavBar>

            <div className="skeleton">
                <div className="detail">
                    <div className="thumb">
                        <React.UI.Image src={room.thumb_text} />
                    </div>
                    <div className="right">
                        <p>{room.name}</p>
                        <div className="tips">
                            <span>{room.area}㎡</span>
                            <span>宜住{room.live}人</span>
                        </div>
                    </div>
                </div>
                <div className="skeleton_rect">

                    <div className="item">
                        <label>入住日期</label>
                        <React.UI.Input value={order.datestr} type="text" className="item_right" placeholder="请选择入住日期" onClick={() => SetShow(true)} />

                        <React.UI.CalendarPicker
                            visible={show}
                            min={new Date()}
                            defaultValue={[todaystr,tomorrowstr]}
                            selectionMode='range'
                            onClose={() => SetShow(false)}
                            onMaskClick={() => SetShow(false)}
                            onConfirm={DateChange}
                        >

                        </React.UI.CalendarPicker>
                    </div>
                    <div className="item">
                        <label>住客信息</label>
                        <React.UI.Input
                            value={order.gueststr}
                            type="text"
                            className="item_right"
                            placeholder="请选择住客信息"
                            onClick={() => SetShowguest(true)}
                        />

                        <React.UI.Popup
                            visible={showguest}
                            onMaskClick={() => {
                                SetShowguest(false)
                            }}
                        >

                            <span className='confirms' onClick={() => { SetShowguest(false) }}>
                                确认
                            </span>
                            <div className="checkListContainer">

                                <React.UI.CheckList
                                    multiple
                                    className="myCheckList"
                                    defaultValue={selected ? [selected] : []}

                                    onChange={guestchange}
                                >
                                    <div
                                        style={{ height: '40vh', overflowY: 'scroll', padding: '20px' }}
                                    >

                                        {guest.map((item: any, key) =>
                                            <React.UI.CheckList.Item value={item.id} key={key}>
                                                {item.nickname}
                                            </React.UI.CheckList.Item>
                                        )}
                                    </div>
                                </React.UI.CheckList>
                            </div>

                        </React.UI.Popup>

                    </div>
                </div >
                <div className="skeleton_price">
                    <div className="tips">优惠券</div>
                    <p>{order.couponstr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetCouponShow(true)}>选择</React.UI.Button>
                    <React.UI.Picker
                        columns={coupon}
                        visible={CouponShow}
                        onClose={() => {
                            SetCouponShow(false)
                        }}
                        onConfirm={CounponConfirm}
                    ></React.UI.Picker>

                </div>
                <div className="skeleton_price">
                    <div className="tips">房间费用</div>
                    <div className="prices">
                        <span>￥{origin_price}</span>
                        <span>共 {order.days} 晚</span>
                    </div>
                </div>
            </div >
            <div className="comfirm_foot-bar">
                <div className="text">
                    <span>总价:</span>
                    <span>￥{price}</span>
                </div>

                <React.UI.Button color="primary" onClick={submit} >提交订单</React.UI.Button>

            </div>




        </>
    )
}


export default Confirm;